package com.example.leetcode.leetcode.hot100;

/**
 * @author haitao
 * @date 2021/8/27 10:08 上午
 * <p>
 * 5 6 1 2 3 4
 * 5
 */
public class Solution33 {

    public int search(int[] nums, int target) {

        if (nums.length == 0) {
            return -1;
        }
        if (nums.length == 1) {
            return target == nums[0] ? 0 : -1;
        }

        // 找旋转中心点
        int n = nums.length - 1;
        int l = 0, r = n;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            // 一种情况是mid >= nums[0], 说明左侧是有序的，否者无法保证左侧有序
            if (nums[mid] >= nums[0]) {
                // 如果target在左侧范围内
                if (target >= nums[0] && target < nums[mid]) {
                    r = mid - 1;
                }
                // 右侧无序重新处理
                else {
                    l = mid + 1;
                }
            }
            // mid < nums[0]，说明左侧是无序的
            else {
                // 如果右侧是有序的，并且target在右侧
                if (target > nums[mid] && target <= nums[n]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        // 二分查找
        return -1;
    }

    public static void main(String[] args) {
        Solution33 solution33 = new Solution33();
        int [] nums = new int[]{4,5,6,7,0,1,2,0};
        System.out.println(solution33.search(nums,6));
    }
}
